package cn.edu.cdtu.healthserver.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.edu.cdtu.healthserver.domain.LoginJson;
import cn.edu.cdtu.healthserver.domain.UserInformation;
import cn.edu.cdtu.healthserver.service.LoginControl;
import cn.edu.cdtu.healthserver.service.UserService;
import cn.edu.cdtu.healthserver.service.impl.UserServiceImplementation;
import cn.edu.cdtu.healthserver.utils.ConnectUtil;

import com.google.gson.Gson;

/**
 * Servlet implementation class LoginServlet
 * 后台中负责处理登录的Servlet。
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private UserService userService = new UserServiceImplementation();
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		//设置接收到的来自客户端的信息的编码格式。
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		//获取来自客户端的用户信息。（为字符串）
		String account=request.getParameter(
				ConnectUtil.LoginPargrams.Pargram.LOGIN_ACCOUNT);
		String password=request.getParameter(
				ConnectUtil.LoginPargrams.Pargram.LOGIN_PASSWORD);
		//检测用户信息，并返回结果
		UserInformation loginUser = userService.CheckLogin(account, password);
		LoginJson loginJson = new LoginJson();
		//对检测的结果进行处理，并将结果返回给手机上的客户端。
		//第一个为登录的用户不存在的情况
		if(loginUser != null)
		{
			loginJson.setStatus(1);
			loginJson.setUserInformation(loginUser);
			LoginControl.setLoginedUer(request, loginUser);
		}
		//用户身份存在。
		else
		{
			loginJson.setStatus(0);
			loginJson.setUserInformation(null);
		}
		Gson gson=new Gson();
		String LoginJsonString = gson.toJson(loginJson);
		//发送结果到手机上。
		response.setContentType(ConnectUtil.ContentTypeString.jSON_STRING);
		PrintWriter writer = response.getWriter();
		writer.write(LoginJsonString);
		writer.flush();
		writer.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doGet(request, response);
	}

}
